﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace Zgq.CommonTools
{
    public static class HttpHelper
    {
        public static string UrlEncode(this string urlStr)
        {
            string str = null;
            try
            {
                str = System.Web.HttpUtility.UrlEncode(urlStr, Encoding.UTF8);
            }
            catch
            {
                str = urlStr;
            }
            return str;
        }

        public static string UrlDecode(this string urlStr)
        {
            string str = null;
            try
            {
                str = System.Web.HttpUtility.UrlDecode(urlStr, Encoding.UTF8);
            }
            catch
            {
                str = urlStr;
            }
            return str;
        }

        /// <summary>
        /// GET请求与获取结果
        /// </summary>
        public static string HttpGet(string Url, string postDataStr, Encoding charset)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        public static string HttpPostRespone(string url, Dictionary<string, object> paramDic)
        {
            StringBuilder paramStr = new StringBuilder();
            foreach (var v in paramDic)
            {
                paramStr.AppendFormat("{0}={1}&", v.Key, v.Value);
            }

            return HttpPost(url, paramStr.ToString(), Encoding.UTF8);
        }
        /// <summary>  
        /// POST请求与获取结果  
        /// </summary>  
        public static string HttpPost(string Url, string postDataStr, Encoding charset)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            //request.ContentLength = postDataStr.Length;
            //StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.UTF8);
            //writer.Write(postDataStr);
            //writer.Flush();

            byte[] data = charset.GetBytes(postDataStr);
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encoding = response.ContentEncoding;
            //if (encoding == null || encoding.Length < 1)
            //{
            //    encoding = "UTF-8"; //默认编码  
            //}
            encoding = "UTF-8"; //默认编码  
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
            string retString = reader.ReadToEnd();
            return retString;
        }

        /// 异步调用
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <param name="callBackAction"></param>
        /// <returns></returns>
        public static void HttpPostAysc(string Url, string postDataStr, Encoding charset, Action<string> callBackAction)
        {
            Func<string> func = () =>
            {
                return HttpPost(Url, postDataStr, charset);
            };

            func.BeginInvoke((ar) =>
            {
                var result = func.EndInvoke(ar);
                callBackAction.Invoke(result);
            }, null);
        }


        /// <summary>
        /// 获取网页内容
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="isUtf8">是否为utf8编码</param>
        /// <returns></returns>
        public static string GetWebSiteContent(string url, bool isUtf8 = true)
        {
            WebClient MyWebClient = new WebClient();

            MyWebClient.Credentials = CredentialCache.DefaultCredentials;//获取或设置用于向Internet资源的请求进行身份验证的网络凭据

            Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据

            string pageHtml;

            if (isUtf8)
                pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8，则使用这句
            else
                pageHtml = Encoding.Default.GetString(pageData);  //如果获取网站页面采用的是GB2312，则使用这句            


            return pageHtml;
        }
    }
}
